<script setup>
import { ref, onMounted } from 'vue'
import {
  businessPageQueryService,
  acceptBusinessService,
  completeBusinessService,
  refundBusinessService
} from '@/api/business.js'
import { Search, Refresh, DCaret, CaretTop, CaretBottom } from '@element-plus/icons-vue'
import ProjectTypeSelect from '../project/components/ProjectTypeSelect.vue'
import BusinessEdit from './components/BusinessEdit.vue'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'

const route = useRoute()

// 获取用户角色
const userStore = useUserStore()
const userRole = userStore.user.role

const businessList = ref([]) // 业务列表
const total = ref(0) // 总条数
const loading = ref(false) // loading状态

// 请求参数
const params = ref({
  pageNum: 1, // 当前页码
  pageSize: 10, // 每页条数
  orderBy: 'update_time', // 排序字段
  isAsc: false, // 是否升序
  projectName: null, // 服务项目名称
  projectTypeId: null, // 服务项目类型id
  employeeName: null, // 员工姓名
  memberName: null, // 会员姓名
  plateNumber: null, // 车牌号
  payMethod: null, // 付款方式
  businessStatus: null, // 业务状态
  startTime: null, // 开始时间
  endTime: null // 结束时间
})

// 业务状态与el-tag类型映射
const businessStatusTagTypeMap = {
  待接单: 'info',
  进行中: 'primary',
  已完成: 'success',
  已退款: 'warning'
}
const getBusinessStatusTagType = (status) => {
  return businessStatusTagTypeMap[status] || 'info'
}

// 基于params参数，获取业务列表
const getBusinessList = async () => {
  loading.value = true
  const res = await businessPageQueryService(params.value)
  businessList.value = res.data.data.list
  total.value = res.data.data.total
  loading.value = false
}

// 初始化数据，可以接收路由参数
onMounted(() => {
  params.value.startTime = route.query.startTime || null
  params.value.businessStatus = route.query.businessStatus || null
  getBusinessList()
})

// 处理分页逻辑
const onPageSizeChange = (size) => {
  params.value.pageNum = 1
  params.value.pageSize = size
  getBusinessList()
}
const onPageNumChange = (page) => {
  params.value.pageNum = page
  getBusinessList()
}

// 处理排序逻辑
const handleSort = (field) => {
  if (params.value.isAsc === false && params.value.orderBy === field) {
    // 如果当前已经降序，则重置排序
    params.value.orderBy = null
    params.value.isAsc = null
  } else if (params.value.orderBy === field) {
    // 如果当前已经是按该字段排序，则切换升序/降序
    params.value.isAsc = !params.value.isAsc
  } else {
    // 如果是第一次点击该字段，则默认升序
    params.value.orderBy = field
    params.value.isAsc = true
  }
  // 重新获取数据
  getBusinessList()
}

// 获取排序图标
const getSortIcon = (field) => {
  if (params.value.orderBy === field) {
    return params.value.isAsc ? CaretTop : CaretBottom
  }
  return DCaret
}

// 搜索逻辑
const handleSearch = () => {
  params.value.pageNum = 1
  getBusinessList()
}

// 重置逻辑
const handleReset = () => {
  params.value = {
    ...params.value, // 保留其他属性
    pageNum: 1,
    projectName: null,
    projectTypeId: null,
    employeeName: null,
    memberName: null,
    plateNumber: null,
    payMethod: null,
    businessStatus: null,
    startTime: null,
    endTime: null
  }
  getBusinessList()
}

const businessEditRef = ref()
// 新增业务
const handleAdd = () => {
  businessEditRef.value.open()
}

// 业务接单
const handleAccept = async (row) => {
  await ElMessageBox.confirm('是否确认业务接单？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await acceptBusinessService(row.id)
  ElNotification({
    title: '业务接单成功',
    type: 'success'
  })
  getBusinessList()
}

// 完成业务
const handleComplete = async (row) => {
  await ElMessageBox.confirm('是否确认完成业务？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await completeBusinessService(row.id)
  ElNotification({
    title: '完成业务成功',
    type: 'success'
  })
  getBusinessList()
}

// 业务退款
const handleRefund = async (row) => {
  await ElMessageBox.confirm('是否确认业务退款？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await refundBusinessService(row.id)
  ElNotification({
    title: '业务退款成功',
    type: 'success'
  })
  getBusinessList()
}

// 显示服务项目信息
const activeProjectId = ref() // 当前需要显示的服务项目ID
const showProjectInfoForm = (projectId) => {
  activeProjectId.value = projectId
}

// 显示员工信息
const activeEmployeeId = ref() // 当前需要显示的员工ID
const showEmployeeInfoForm = (employeeId) => {
  if (employeeId) {
    activeEmployeeId.value = employeeId
  }
}

// 显示会员信息
const activeMemberId = ref() // 当前需要显示的会员ID
const showMemberInfoForm = (memberId) => {
  activeMemberId.value = memberId
}
</script>

<template>
  <page-container title="业务管理">
    <template #extra>
      <el-button
        v-if="['管理员', '店长', '收银员'].includes(userRole)"
        type="primary"
        plain
        @click="handleAdd"
        >新增业务</el-button
      >
    </template>
    <!-- 表单 -->
    <el-form inline>
      <el-form-item label="服务项目名称:"
        ><el-input v-model="params.name" placeholder="请输入"
      /></el-form-item>
      <el-form-item label="服务项目类型:">
        <project-type-select v-model="params.projectTypeId" width="200px" />
      </el-form-item>
      <el-form-item label="员工姓名:"
        ><el-input v-model="params.employeeName" placeholder="请输入"
      /></el-form-item>
      <el-form-item label="会员姓名:"
        ><el-input v-model="params.memberName" placeholder="请输入"
      /></el-form-item>
      <el-form-item label="车牌号:"
        ><el-input v-model="params.plateNumber" placeholder="请输入"
      /></el-form-item>
      <el-form-item label="付款方式:">
        <el-select v-model="params.payMethod" style="width: 100px">
          <el-option label="余额" value="余额"></el-option>
          <el-option label="微信" value="微信"></el-option>
          <el-option label="支付宝" value="支付宝"></el-option>
          <el-option label="现金" value="现金"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="业务状态:">
        <el-select v-model="params.businessStatus" style="width: 100px">
          <el-option label="待接单" value="待接单"></el-option>
          <el-option label="进行中" value="进行中"></el-option>
          <el-option label="已完成" value="已完成"></el-option>
          <el-option label="已退款" value="已退款"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间:">
        <el-date-picker
          v-model="params.startTime"
          type="datetime"
          placeholder="选择开始时间"
          format="YYYY/MM/DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="结束时间:">
        <el-date-picker
          v-model="params.endTime"
          type="datetime"
          placeholder="选择结束时间"
          format="YYYY/MM/DD hh:mm:ss"
          value-format="YYYY-MM-DD hh:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleSearch"></el-button>
        <el-button type="default" :icon="Refresh" @click="handleReset"></el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table class="tb" :data="businessList" v-loading="loading" :row-style="{ height: '50px' }">
      <el-table-column prop="id" label="业务ID" width="100">
        <template #header>
          <span>业务ID</span>
          <el-icon @click="handleSort('id')">
            <component :is="getSortIcon('id')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="projectName" label="服务项目名称" width="200">
        <template #default="{ row }">
          <el-popover effect="light" trigger="click" placement="right" :width="600">
            <template #reference>
              <el-tag @click="showProjectInfoForm(row.projectId)">{{ row.projectName }}</el-tag>
            </template>
            <ProjectInfoForm v-if="activeProjectId === row.projectId" :projectId="row.projectId" />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="employeeName" label="员工姓名" width="120">
        <template #default="{ row }">
          <el-popover effect="light" trigger="click" placement="right" :width="600">
            <template #reference>
              <el-tag
                :type="row.employeeName ? 'primary' : 'info'"
                @click="showEmployeeInfoForm(row.employeeId)"
                >{{ row.employeeName ?? '未接单' }}</el-tag
              >
            </template>
            <EmployeeInfoForm
              v-if="activeEmployeeId === row.employeeId"
              :employeeId="row.employeeId"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="memberName" label="会员姓名" width="120">
        <template #default="{ row }">
          <el-popover effect="light" trigger="click" placement="right" :width="600">
            <template #reference>
              <el-tag @click="showMemberInfoForm(row.memberId)">{{ row.memberName }}</el-tag>
            </template>
            <MemberInfoForm v-if="activeMemberId === row.memberId" :memberId="row.memberId" />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="carPlateNumber" label="车牌号" width="120" />
      <el-table-column prop="actualDuration" label="实际服务时长" width="120">
        <template #default="{ row }">
          <div>{{ row.actualDuration ?? '---' }}分钟</div>
        </template>
      </el-table-column>
      <el-table-column prop="payableAmount" label="付款金额" width="120">
        <template #default="{ row }">
          <div>{{ (row.payableAmount / 100).toFixed(2) }}元</div>
        </template>
      </el-table-column>
      <el-table-column prop="payMethod" label="付款方式" width="100" />
      <el-table-column prop="status" label="业务状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getBusinessStatusTagType(row.status)">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #header>
          <span>创建时间</span>
          <el-icon @click="handleSort('create_time')">
            <component :is="getSortIcon('create_time')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #header>
          <span>更新时间</span>
          <el-icon @click="handleSort('update_time')">
            <component :is="getSortIcon('update_time')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="{ row }">
          <el-button
            v-if="['店长', '服务员'].includes(userRole) && row.status === '待接单'"
            type="primary"
            plain
            size="small"
            @click="handleAccept(row)"
            >接单</el-button
          >
          <el-button
            v-if="
              ['管理员', '店长', '收银员', '服务员'].includes(userRole) && row.status === '进行中'
            "
            type="success"
            plain
            size="small"
            @click="handleComplete(row)"
            >完成</el-button
          >
          <el-button
            v-if="['管理员', '店长', '收银员'].includes(userRole) && row.status === '待接单'"
            type="danger"
            plain
            size="small"
            @click="handleRefund(row)"
            >退款</el-button
          >
          <el-tag v-if="['已完成', '已退款'].includes(row.status)" type="info">不可操作</el-tag>
        </template>
      </el-table-column>
      <!-- 空数据提示 -->
      <template #empty>
        <el-empty description="没有数据"></el-empty>
      </template>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="params.pageNum"
      v-model:page-size="params.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="onPageSizeChange"
      @current-change="onPageNumChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </page-container>
  <!-- 抽屉 -->
  <business-edit ref="businessEditRef" @success="handleReset"></business-edit>
</template>

<style lang="scss" scoped>
.tb {
  border-radius: 10px;
  box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}
</style>
